//index.js
//获取应用实例
var cfg = require('../../utils/cfg');
var util = require('../../utils/util');
var moneyUtil = require('../../utils/moneyUtil');
const app = getApp();
const { $Toast } = require('../../dist/base/index');
var common = require('../../utils/common');
var sendRequest = require('../../utils/requestUtils');

Page({
  data: {
    merchant : {},
    commoditys : [],
    totalMoney : 0,
    payMoney : 0,
    countDot : 0,
    cardhidden : true,
    cardCommos : [],
    skuCommo : {},
    skuPageHidden : true,
    caidanHidden : false,
    dibuHidden : false
  },
  onLoad: function (options) {
    let that = this;
    let merchant = JSON.parse(options.merchant);
    console.log(merchant);

    that.setData({
      merchant: merchant
    });
    that.loadCaidans(merchant.id);
  },

  //处理+-事件
  processCard: function (flag, commodityId) {
    let that = this;
    let commo = that.findCommo(commodityId);
    //需要展示SKU选择界面
    if (commo.chose) {
      if (flag == 1) {
        that.showSKU(commo);
      } else {
        that.showCard()
      }
      return;
    }

    //不需要展示SKU
    if (flag == 1) {
      that.createSkuCommo(commo);
      that.commonAdd(that.data.skuCommo, 1);
    } else {
      let cardCommos = that.data.cardCommos;
      let cardCommon = undefined;
      for (let i = 0; i < cardCommos.length; i++) {
        if (commo.id == cardCommos[i].vid) {
          cardCommon = cardCommos[i];
        }
      }
      if (cardCommon == undefined) {
        return;
      }
      that.commonSub(cardCommon);
    }
  },

  addToTrolley : function(event) {
    let that = this;
    let commodityId = event.currentTarget.dataset.commodityId;
    that.processCard(1, commodityId);
  },

  removeFromTrolley: function (event) {
    let that = this;
    let commodityId = event.currentTarget.dataset.commodityId;
    that.processCard(0, commodityId);
  },

  //sku +
  addToTrolley2: function () {
    let that = this;
    let skuCommo = that.data.skuCommo;
    skuCommo.numb ++;
    that.setData({
      skuCommo: skuCommo
    });
  },

  //sku -
  removeFromTrolley2: function (event) {
    let that = this;
    let skuCommo = that.data.skuCommo;
    if (skuCommo.numb <= 1) {
      return;
    }
    skuCommo.numb --;
    that.setData({
      skuCommo: skuCommo
    });
  },

  //购物车 +
  addToTrolley3: function (event) {
    let that = this;
    let vid = event.currentTarget.dataset.commodityId;
    let cardCommos = that.data.cardCommos;
    let cardCommon = undefined;
    for (let i = 0; i < cardCommos.length; i++) {
      if (vid == cardCommos[i].vid) {
        cardCommon = cardCommos[i];
      }
    }

    if (cardCommon == undefined) {
      return;
    }

    that.commonAdd(cardCommon, 1);
  },

  //购物车 -
  removeFromTrolley3: function (event) {
    let that = this;
    let vid = event.currentTarget.dataset.commodityId;
    let cardCommos = that.data.cardCommos;
    let cardCommon = undefined;
    for (let i = 0; i < cardCommos.length; i++) {
      if (vid == cardCommos[i].vid) {
        cardCommon = cardCommos[i];
      }
    }

    if (cardCommon == undefined) {
      return;
    }

    that.commonSub(cardCommon);
  },

  findCommo : function(commoId) {
    let that = this;
    let commos = that.data.commoditys;
    for (let i = 0; i < commos.length; i++) {
      if (commos[i].id == commoId) {
        return commos[i];
      }
    }
  },

  //展示购物车
  showCard : function() {
    let that = this;
    let cardhidden = !that.data.cardhidden;
    that.setData({
      cardhidden: cardhidden,
      caidanHidden: !cardhidden
    });
  },

  //展示sku界面
  showSKU: function (commo) {
    let that = this;
    that.createSkuCommo(commo);
    that.setData({
      skuCommo: commo,
      skuPageHidden : false,
      skuCommo: that.data.skuCommo,
      caidanHidden : true,
      dibuHidden: true
    });
  },

  //关闭sku界面
  closeSKu : function() {
    let that = this;
    that.setData({
      skuPageHidden: true,
      caidanHidden: false,
      dibuHidden: false
    });
  },

  //创建新的sku商品
  createSkuCommo : function(commo) {
    let that = this;
    let skuCommo = JSON.parse(JSON.stringify(commo));
    skuCommo.numb = 1;
    skuCommo.vid = commo.id;
    skuCommo.skuDesc = '';
    that.data.skuCommo = skuCommo;
  },

  //加入购物车
  addCard : function() {
    let that = this;
    let skuCommo = that.data.skuCommo;
    skuCommo.skuDesc = '';

    if (skuCommo.kouweis.length != 0) {
      let sku = that.getSkuSel(skuCommo.kouweis);
      if (sku == undefined) {
        util.alert('请选择口味');
        return;
      }
      skuCommo.vid += '-' + sku.id
      skuCommo.skuDesc = sku.skuName + ' '
      skuCommo.kouweiSkuId = sku.id;
    }

    if (skuCommo.guiges.length != 0) {
      let sku = that.getSkuSel(skuCommo.guiges);
      if (sku == undefined) {
        util.alert('请选择规格');
        return;
      }
      skuCommo.vid += '-' + sku.id;
      skuCommo.price = sku.price;
      skuCommo.skuDesc += sku.skuName;
      skuCommo.guigeSkuId = sku.id;
    }

    that.commonAdd(skuCommo);
    that.closeSKu();
  },

  //通用+商品
  commonAdd : function(skuCommon, buyNum) {
    let that = this;
    let cardCommos = that.data.cardCommos;

    let cardCommon = undefined;
    for (let i=0; i<cardCommos.length; i++) {
      if (skuCommon.vid == cardCommos[i].vid) {
        cardCommon = cardCommos[i];
      }
    }

    buyNum = buyNum == undefined ? skuCommon.numb : buyNum;

    //购物车里木有此商品
    if (cardCommon == undefined) {
      cardCommos.push(skuCommon);
      cardCommon = skuCommon;
    } else {
      cardCommon.numb += buyNum;
    }

    let countDot = that.data.countDot;
    let totalMoney = that.jisuanMoeny(skuCommon, buyNum);
    let payMoney = that.jisuanRealMoney(skuCommon, totalMoney);

    let commondity = that.findCommo(cardCommon.id);
    commondity.numb += buyNum;

    that.setData({
      cardCommos: cardCommos,
      countDot: countDot + buyNum,
      totalMoney: totalMoney,
      payMoney: payMoney,
      commoditys: that.data.commoditys
    });

  },

  //通用-商品
  commonSub: function (cardCommon) {
    let that = this;
    let cardCommos = that.data.cardCommos;
    if (cardCommon.numb <= 0) {
      return;
    }

    cardCommon.numb -= 1;

    let countDot = that.data.countDot;
    let totalMoney = that.jisuanMoeny(cardCommon, 1, false);
    let payMoney = that.jisuanRealMoney(cardCommon, totalMoney);

    if (cardCommon.numb == 0) {
      let indexValue = -1;
      for (let i = 0; i < cardCommos.length; i++) {
        if (cardCommon.vid == cardCommos[i].vid) {
          indexValue = i;
          break;
        }
      }
      cardCommos.splice(indexValue, 1);
    }

    let commondity = that.findCommo(cardCommon.id);
    commondity.numb -= 1;

    that.setData({
      cardCommos: cardCommos,
      countDot: --countDot,
      totalMoney: totalMoney,
      payMoney: payMoney,
      commoditys: that.data.commoditys
    });
  },

  jisuanRealMoney: function (currentComm, totalMoney) {
    let that = this;
    let payMoney = totalMoney;
    if (that.data.merchant.skus.length == 0) {
      return payMoney;
    }

    let finalSku = undefined;

    for (let i = 0; i < that.data.merchant.skus.length; i++) {
      let sku = that.data.merchant.skus[i];
      console.log('value1=' + sku.value1);
      let manMoney = moneyUtil.moneyUtils.toInteger(sku.value1).num;
      console.log('manMoney=' + manMoney);
      if (moneyUtil.moneyUtils.toInteger(payMoney+'').num >= manMoney) {
        finalSku = sku;
      }
    }

    if (finalSku == undefined) {
      return payMoney;
    }

    payMoney = moneyUtil.moneyUtils.subtract(payMoney+'', finalSku.value2, 2);
    console.log('payMoney=' + payMoney);

    return payMoney;
  },

  jisuanMoeny: function (currentComm, buyNum, flag) {
    let that = this;
    let xiaoji = moneyUtil.moneyUtils.multiply(buyNum, currentComm.price, 2);

    let money = flag === undefined ? moneyUtil.moneyUtils.add(xiaoji, that.data.totalMoney, 2) :
      moneyUtil.moneyUtils.subtract(that.data.totalMoney,xiaoji, 2);

    console.log('money=' + money);
    return money;
  },

  //口味tag点击事件
  kouweiSkuChange : function(event) {
    let that = this;
    let skuId = event.detail.name;
    let selFlag = event.detail.checked;
    if (!selFlag) {
      return;
    }
    console.log("skuId=" + skuId);

    let skuCommo = that.data.skuCommo;
    let sku = that.findSku(skuCommo.kouweis, skuId);

    sku.chose = selFlag;
    that.setData({
      skuCommo: skuCommo
    });
  },

  //规格tag点击事件
  guigeSkuChange: function (event) {
    let that = this;
    let skuId = event.detail.name;
    let selFlag = event.detail.checked;
    if (!selFlag) {
      return;
    }
    console.log("skuId=" + skuId);

    let skuCommo = that.data.skuCommo;
    let sku = that.findSku(skuCommo.guiges, skuId);

    sku.chose = selFlag;
    skuCommo.price = sku.price;
    that.setData({
      skuCommo: skuCommo
    });

  },

  //获取被选中的sku
  getSkuSel : function(skus) {
    let sku = undefined;
    for (let i=0; i<skus.length; i++) {
      if (skus[i].chose) {
        sku = skus[i];
      }
    }
    return sku;
  },

  findSku : function(skus, skuId) {
    let xx = undefined;
    for (let i=0; i<skus.length; i++) {
      if (skus[i].id == skuId) {
        xx = skus[i];
      }
      skus[i].chose = false;
    }
    return xx;
  },

  //加载所有的菜单数据
  loadCaidans : function(id) {
    let that = this;
    sendRequest.sendReq(cfg.djurl.listCommodity, {
      merchantId: id
    }, function (result) {
      let commoditys = result.data;
      that.setData({
        commoditys: commoditys
      });
    });
  },

  //去结算
  toSettle: function () {
    let that = this;
    console.log('去结算...');

    let cardCommos = that.data.cardCommos;

    if (cardCommos.length == 0) {
      util.alert('您的购物车是空的');
      return;
    }

    let buyCommons = [];
    for (let i=0; i<cardCommos.length; i++) {
      let buyCommon = {};
      let cardCommo = cardCommos[i];

      buyCommon.id = cardCommo.id;
      buyCommon.merchantId = cardCommo.merchantId;
      buyCommon.commName = cardCommo.commName;
      buyCommon.price = cardCommo.price;
      buyCommon.numb = cardCommo.numb;
      buyCommon.kouweiSkuId = cardCommo.kouweiSkuId;
      buyCommon.guigeSkuId = cardCommo.guigeSkuId;
      buyCommon.chose = cardCommo.chose;
      buyCommon.remark = cardCommo.chose ? cardCommo.skuDesc : '';

      buyCommons.push(buyCommon);
    }

    //创建订单
    sendRequest.sendReq(cfg.djurl.settleOrder, {
      openId: app.globalData.openId,
      merchantId: that.data.merchant.id,
      settleInfo: JSON.stringify(buyCommons)
    }, function (result) {
      wx.navigateTo({
        url: '/pages/settle/settle?bizOrderId=' + result.data
      })
    });

  }

})
